package com.example.demo.config;

import com.example.demo.common.AppConstant;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

// 定义拦截规则
@Configuration
public class AppConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")    // 允许跨域访问的路径
                .allowedOriginPatterns("*")            // 允许跨域的源
                .allowedMethods("POST", "GET", "PUT")  // 允许请求的方法
                .maxAge(16800)                  // 预检间隔时间
                .allowedHeaders("*")            // 允许头部设置
                .allowCredentials(true);        // 是否发送 cookie
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/user/reg")
                .excludePathPatterns("/user/login")
                .excludePathPatterns("/images/**");

        // 按顺序拦截, 先执行登录拦截器, 再执行管理员拦截器
        // 管理员拦截器， 拦截管理员的接口。
        registry.addInterceptor(new AdminInterceptor())
                .addPathPatterns("/**/admin/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //配置本地资源映射路径，将url与物理路径进行关联
        registry.addResourceHandler("/images/dish/**")
                .addResourceLocations("file:" + AppConstant.DISH_DIR + "/");

        registry.addResourceHandler("/images/user/**")
                .addResourceLocations("file:" + AppConstant.USER_DIR + "/");
    }
}
